﻿var map, autocompleteService, bounds, searchArr, geocoder, infowindow, locationCityName, minPriceOfSkuInfoDoor, minPriceOfSkuInfoStore;
//店鋪列表
var storeList;
//上門區縣id，根據定位的區縣名稱匹配
var goCustumerDoorAreaCode = 0;
//當前上門定位的氣球
var goDoorMarker;
//切換tab時區別上門還是到店,1=上門，2=到店
var doorOrStore = pageObj.serverType;
//當前手機型號
var phoneModels=null;

$(function () {
    //到店、上门，Tab切换
    mui(".nav-tab").on('tap', 'li', function () {
        $(this).addClass("cur").siblings().removeClass("cur");
        //$(".slect-fault").html(pageObj.words.selectMalfun);
        if ($(this).data("role") === "door") {
            $(".fix-rws .row-sm").removeClass("mui-hidden");
            $(".fix-rws .row-md").addClass("mui-hidden");
            //上門       
            doorOrStore = 1;
            //顯示上門的故障
            //$("#doorMalfun").show();
            //$("#storeMalfun").hide();
            
            $("#minPriceValueDoor").show();
            $("#minPriceValueStore").hide();

            //$("#Model").html("").hide();
            //$("#Trouble").html("").hide();
           
            //$(".rep-tab a").first().addClass("cur").siblings().removeClass("cur");         
            //$("#Brand").show();
            //$("#doorMalfun .box[typeid=Brand]").show();

            //pageObj.fn.loadBrandOnTabChange(1);
            //if (pageObj.serverType == 1 || pageObj.serverType==3) {
            //    //熱門過來故障設置
            //    pageObj.fn.setHotMalfuciton();
            //}
            
            console.log(goDoorMarker);
            if (goDoorMarker!=undefined) {
                pageObj.fn.showMapInfo(goDoorMarker.address, goDoorMarker);
                map.panTo(goDoorMarker.position);
            }    
        } else {
            //到店
            doorOrStore = 2;
            //顯示到店的故障
            //$("#doorMalfun").hide();
            //$("#storeMalfun").show();

            $("#minPriceValueDoor").hide();
            $("#minPriceValueStore").show();
            //$("#Model").html("").hide();
            //$("#Trouble").html("").hide();

            //$(".rep-tab a").first().addClass("cur").siblings().removeClass("cur");
            //$("#Brand").show();
            //$("#storeMalfun .box[typeid=Brand]").show();
            
            //地圖定位店鋪坐標
            var storeSysNo = $(".slect-store .md-itm").attr("storesysno");
            //pageObj.fn.loadBrandOnTabChange(2);
            //if (pageObj.serverType == 2 || pageObj.serverType == 3) {
            //    //熱門過來故障設置
            //    pageObj.fn.setHotMalfuciton();
            //}
            pageObj.fn.mapPantoStore(storeSysNo);

            $(".fix-rws .row-sm").addClass("mui-hidden");
            $(".fix-rws .row-md").removeClass("mui-hidden");
        };
    });
    //门店选择
    mui(".fix-rws").on('tap', '.slect-store', function () {
        $('.pop-md').show();
        pageObj.fn.inputPhoneBlur();
    });
    mui(".pop-md").on('tap', '.btn-ok', function () {
        $('.pop-md').hide();
    });
    mui(".pop-md").on('tap', '.btn-gb', function () {
        $('.pop-md').hide();
    });
    mui(".pop-md .md-ul").on('tap', 'li', function () {
        var oGz = $(this).html();
        console.log('門店選擇：');
        console.log(oGz);
        var storeSysNo = $(this).find(".md-itm").attr("storesysno");
        pageObj.fn.mapPantoStore(storeSysNo);

        $(this).addClass("cur").siblings().removeClass("cur");
        //设置选中门店
        $(".slect-store").html(oGz);
        //关闭门店弹窗
        $('.pop-md').hide();
    });
    //地址选择
    mui(".fix-rws").on('tap', '.slect-map', function () {
        $('.pop-dz').show();
        pageObj.fn.inputPhoneBlur();
    });
    mui(".pop-dz").on('tap', '.btn-gb', function () {
        $('.pop-dz').hide();
    });
    //输入地址，清除地址
    mui(".pop-dz .row-cdz").on('tap', 'input', function () {
        $(this).parent().children('.icon-clear').show();
    });
    mui(".pop-dz .row-cdz").on('tap', '.icon-clear', function () {
        $(this).parent().children('input').val("");
        $(this).hide();
    });
    //故障选择
    mui(".fix-rws").on('tap', '.slect-fault', function () {
        //$('.pop-gz').show();
        pageObj.fn.inputPhoneBlur();
        //顯示品牌
        if (doorOrStore == 1) {
            $("#doorMalfun").show();
            $("#storeMalfun").hide();
            //$("#doorMalfun div[typeid=Trouble]").show();
        } else {
            //$("#storeMalfun div[typeid=Trouble]").show();
            $("#storeMalfun").show();
            $("#doorMalfun").hide();
        }
    });
    //故障選擇確定按鈕
    mui(".pop-gz").on('tap', '.btn-ok', pageObj.fn.sureMalfunBtn);
    mui(".pop-gz").on('tap', '.btn-gb', function () {
        $('.pop-gz').hide();
    });
    //选择故障
    $(".rep-box").find(".box:first").show();
    mui(".rep-tab").on('tap', 'a', function () {
        var index = $(this).index();
        $(this).parent().next().find(".box").hide().eq(index).show();
        $(this).addClass("cur").siblings().removeClass("cur");
    });
    // 手机维修数组（品牌，型号，故障）
    //var myReps = new Array();
    mui(".rep-box .box").on('tap', 'p', function () {
     
        $(this).addClass("cur").siblings().removeClass("cur");
        //新增打开下一个tab
        var index = $(this).parent(".box").index();
        console.log($(this).html());
        console.log(index);
        if (index == 0) {
            //切換到型號顯示，隱藏手機品牌
            //手機品牌
            //myReps[0] = $(this).html();         
            //品牌主鍵
            var brandSysNo = $(this).attr("sysNo");
            //加載選中品牌下手機型號列表
            pageObj.fn.loadPhoneModels(brandSysNo, doorOrStore);
            console.log($(this).html());
            if (doorOrStore == 1) {
                $("#doorMalfun").find(".box").hide().eq(1).show();
                $("#doorMalfun .rep-tab").find("a").eq(1).addClass("cur").siblings().removeClass("cur");
            } else {
                $("#storeMalfun").find(".box").hide().eq(1).show();
                $("#storeMalfun .rep-tab").find("a").eq(1).addClass("cur").siblings().removeClass("cur");
            }
            //$(".rep-box").find(".box").hide().eq(1).show();
            //$(".rep-tab").find("a").eq(1).addClass("cur").siblings().removeClass("cur");
        } else if (index == 1) {
            //手機型號
            //myReps[1] = $(this).html();
            console.log($(this).html());
            //手機型號主鍵
            var modelSysNo = $(this).attr("modelSysNo");
            //加載選中的手機型號下的故障類型列表
            pageObj.fn.loadMalfuns(modelSysNo, doorOrStore);

            if (doorOrStore == 1) {
                $("#doorMalfun").find(".box").hide().eq(2).show();
                $("#doorMalfun .rep-tab").find("a").eq(2).addClass("cur").siblings().removeClass("cur");
            } else {
                $("#storeMalfun").find(".box").hide().eq(2).show();
                $("#storeMalfun .rep-tab").find("a").eq(2).addClass("cur").siblings().removeClass("cur");
            }
            //$(".rep-box").find(".box").hide().eq(2).show();
            //$(".rep-tab").find("a").eq(2).addClass("cur").siblings().removeClass("cur");
        }
        //else {
        //    //故障類型
        //    //myReps[2] = $(this).html();
        //    console.log($(this).html());
        //};
    });
    mui(".pop-gz .pop-tit").on('tap', '.btn-ok', function () {
        $(".flay-rep").hide();
        //顯示故障信息到標籤
        pageObj.fn.getMalfunTxtToShow(doorOrStore);
        pageObj.hotPageParames.skuSysNO = "0";
        //設置另一個tab是否可能選中故障，表示當前spu支持所有
        if (doorOrStore == 1) {
            //2到店可能選中
            //先獲取上門已經選擇的數據
            var selectParentObj = $("#doorMalfun");
            var brandSysNo = selectParentObj.find("div[typeid=Brand] .cur").first().attr("sysno");
            var phoneModel = selectParentObj.find("div[typeid=Model] .cur").first().attr("modelsysno");
            var malfunctionSysNo = selectParentObj.find("div[typeid=Trouble] .cur").first().attr("malfunctionsysno");
            pageObj.hotPageParames.brandCategorySysno = brandSysNo;
            pageObj.hotPageParames.typeCategorySysno = phoneModel;
            pageObj.hotPageParames.malfunctionsSysNo = malfunctionSysNo;
            pageObj.fn.setHotMalfuciton(2);
        } else {
            //1上門可能選中
             //先獲取到店已經選擇的數據
            var selectParentObj = $("#storeMalfun");
            var brandSysNo = selectParentObj.find("div[typeid=Brand] .cur").first().attr("sysno");
            var phoneModel = selectParentObj.find("div[typeid=Model] .cur").first().attr("modelsysno");
            var malfunctionSysNo = selectParentObj.find("div[typeid=Trouble] .cur").first().attr("malfunctionsysno");
            pageObj.hotPageParames.brandCategorySysno = brandSysNo;
            pageObj.hotPageParames.typeCategorySysno = phoneModel;
            pageObj.hotPageParames.malfunctionsSysNo = malfunctionSysNo; 
            pageObj.fn.setHotMalfuciton(1);
        }       

    });
})
!function () {
    $("#mapApi").height(window.innerHeight - 250);

    pageObj.fn = {
        ajaxError: function (jqXHR, textStatus, errorThrown) {
            var smg = jqXHR.responseText;
            //JSON.stringify(jqXHR.responseText);
            pageObj.fn.alertMsg(smg);
        }
        //彈消息框自動消失
        , alertMsg: function (msg) {
            mui.toast(msg, { duration: 2000, type: 'div' })
        }
        //地址輸入搜索可能結果匹配
        , AutocompleteSearch: function () {
            var address = document.getElementById('txtAutoCompute').value;
            console.log(address);
            if (address == "") {
                return;
            }
            document.getElementById("autoSearchPlace").innerHTML = pageObj.words.loadingMsg + "...";
            function displaySuggestions(predictions, status) {
                if (status != google.maps.places.PlacesServiceStatus.OK) {
                    console.log(status);
                    return;
                }
                searchArr = predictions;
                console.log(predictions);
                //return;
                var htmlArr = new Array();
                predictions.forEach(function (prediction) {
                    var html = '<li placeId="' + prediction.place_id + '" onclick="pageObj.fn.clickAutoAddress(this)">' +
                        '<p class="tit">' + prediction.structured_formatting.main_text + '</p>' +
                        '<p class="txt">' + prediction.description + '</p>' +
                        '</li>';
                    htmlArr.push(html);
                });
                document.getElementById("autoSearchPlace").innerHTML = htmlArr.join('');
            };
            var request = {
                bounds: bounds,
                input: address,
                //types: ['geocode']
            }
            autocompleteService.getPlacePredictions(request, displaySuggestions);
            //autocompleteService.getQueryPredictions(request, displaySuggestions);
        }
        //獲取當前位置定位
        , getPosition: function () {
            if (!navigator.geolocation) {
                //alert("當前不支持html5定位位置");
                pageObj.fn.loadStoreAll();
                pageObj.fn.alertMsg(pageObj.words.notPosion);
                return;
            }
            var options =
                {
                    enableHighAccuracy: true,//高精度定位
                    timeout: 8000,//毫秒，超時時間,超時后調用error
                    maximumAge: 0
                };
            navigator.geolocation.getCurrentPosition(function (position) {
                //console.log('當前定位：');
                //console.log(position);
                var geolocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                //var result_mark = new google.maps.Marker({ position: geolocation });
                //result_mark.setMap(map);
                //map.panTo(geolocation);
                var circle = new google.maps.Circle({
                    center: geolocation,
                    radius: position.coords.accuracy
                });
                //獲取城市名稱
                pageObj.fn.getCityName(geolocation);
                //設置查詢地圖範圍界限
                bounds = circle.getBounds();
                //console.log(circle);
                console.log("定位設置成功");
            }, function (error) {
                pageObj.fn.loadStoreAll();
                //处理错误
                switch (error.code) {
                    case 1:
                        console.log("位置服务被拒绝");
                        pageObj.fn.alertMsg(pageObj.words.noAuthPosition);
                        break;
                    case 2:
                        console.log("暂时获取不到位置信息");
                        pageObj.fn.alertMsg(pageObj.words.getNoPosionInfo);
                        break;
                    case 3:
                        console.log("获取信息超时");
                        pageObj.fn.alertMsg(pageObj.words.getPositionInfoTimeout);
                        break;
                    default:
                        console.log("未知错误");
                        pageObj.fn.alertMsg(pageObj.words.errorUnknow);
                        break;
                }
            }, options);
        }
        //點擊匹配地址
        , clickAutoAddress: function (thisObj) {
            var address = $(thisObj).find(".txt").text();
            var placeId = $(thisObj).attr("placeId");
            console.log(address);
            //$($(".slect-map")[0]).text(address);
            document.getElementById("txtDoorAddress").value = address;
            pageObj.fn.goMapToByPlaceId(placeId);
            //隱藏地址搜索
            $('.pop-dz').hide();
        }
        //根據地址id轉換為地圖坐標
        , goMapToByPlaceId: function (placeId) {
            geocoder.geocode({ 'placeId': placeId }, function (results, status) {
                if (status === 'OK') {
                    var resultPosition = results[0];
                    console.log("定位地址：");
                    console.log(resultPosition);
                    if (resultPosition) {
                        map.setCenter(resultPosition.geometry.location);
                        goDoorMarker = new google.maps.Marker({
                            map: map,
                            position: resultPosition.geometry.location
                        });
                        goDoorMarker.address=   resultPosition.formatted_address;
                        //infowindow.setContent(resultPosition.formatted_address);
                        //infowindow.open(map, marker);
                        pageObj.fn.showMapInfo(resultPosition.formatted_address, goDoorMarker);
                    } else {
                        pageObj.fn.alertMsg(pageObj.words.noResult);
                    }
                } else {
                    pageObj.fn.alertMsg(pageObj.words.positionDecodeError + ":" + status);
                }
            });
        }
        //顯示白色消息框到地圖
        , showMapInfo: function (msg, marker) {
            infowindow.setContent(msg);
            if (marker != null && marker != undefined) {
                infowindow.open(map, marker);
            } else {
                infowindow.open(map);
            }
        }
        //根據經緯度坐標得到城市名稱
        , getCityName: function (latlng) {
            geocoder.geocode({ 'location': latlng }, function (results, status) {
                if (status === 'OK') {
                    console.log(results);
                    //獲取區縣名稱，匹配數據找出區縣id                        
                    var quxian = results.find(w => w.types.filter(x => x == "sublocality_level_1").length > 0);
                    if (quxian != undefined) {
                        var quxianObj = quxian.address_components.find(w => w.types.filter(x => x == "sublocality_level_1").length > 0);
                        if (quxianObj != undefined && quxianObj != null) {
                            console.log("匹配到的區縣名稱=" + quxianObj.short_name);
                            pageObj.fn.marchPositonAreaId(quxianObj.short_name);
                        }
                    }
                    var firstResult = results[0];
                    console.log("定位的詳細地址：");
                    console.log(firstResult);
                    //顯示定位標記
                    goDoorMarker = new google.maps.Marker({
                        map: map,
                        position: latlng
                    });
                    map.panTo(latlng);
                    goDoorMarker.address = firstResult.formatted_address;
                    pageObj.fn.showMapInfo(firstResult.formatted_address, goDoorMarker);

                    //將地址顯示在上門位置地址欄中                     
                    //$(".slect-map").first().html(firstResult.formatted_address);
                    document.getElementById("txtDoorAddress").value = firstResult.formatted_address;
                    if (firstResult) {
                        var city = firstResult.address_components.find(w => w.types.includes("locality"));
                        locationCityName = city.short_name;
                        console.log(city.short_name);
                        //加載此城市的店鋪列表
                        pageObj.fn.loadLocationCityStores();
                    } else {
                        pageObj.fn.alertMsg(pageObj.words.noResult);
                    }
                } else {
                    pageObj.fn.alertMsg(pageObj.words.latLngDecodeError + status);
                }
            });
        }
        //加載定位城市的店鋪列表
        , loadLocationCityStores: function (t) {
            //t=1 測試
            if (t == 1) {
                locationCityName = "成都";
            }
            if (locationCityName == "") {
                return;
            }
            if (locationCityName != "") {
                locationCityName = locationCityName.replace(pageObj.words.citySuffixName, "");
            }
            $.ajax({
                url: pageObj.urlArr.getStores,
                type: "post",
                data: { city: locationCityName },
                success: function (d) {
                    console.log('定位成功獲取的店鋪列表：');
                    console.log(d);
                    if (!d.Status) {
                        pageObj.fn.alertMsg(pageObj.words.handleError + d.Message);
                        return;
                    }
                    if (d.Data.length == 0) {
                        return;
                    }
                    storeList = d.Data;
                    //默認選中第一個
                    //goStoreName//goStoreAddress
                    //document.getElementById("goStoreName").innerHTML = d.Data[0].StoreName;
                    //document.getElementById("goStoreAddress").innerHTML = d.Data[0].Address;
                    var storeArr = [];
                    for (var i = 0; i < d.Data.length; i++) {
                        var item = d.Data[i];
                        var html =
                            '<li ><div class="md-itm" storeSysNo="' + item.SysNo + '" areaCode="' + item.AreaCode + '">' +
                            '<div class="tit cf">' + item.StoreName + '</div>' +
                            '<div class="txt">' + item.Address + '</div>' +
                            '</div></li>';
                        storeArr.push(html);
                        //顯示店鋪標記到地圖
                        //坐標解析
                        //console.log(item.StoreName + "," + item.Address + ",坐標:" + item.GoogleLatLng);
                        var lat = item.GoogleLatLng.split(",")[0];
                        var lng = item.GoogleLatLng.split(",")[1];
                        var positon = { lat: parseFloat(lat), lng: parseFloat(lng) };
                        //console.log(positon);
                        var result_mark = new google.maps.Marker({ position: positon });
                        result_mark.info = item;// { name: item.StoreName, address: item.Address };
                        result_mark.setMap(map);
                        result_mark.addListener("click", function (event) {
                            console.log(this);
                            console.log(event);
                            var storeInfo = "<b>" + this.info.StoreName + "</b><br/>" + pageObj.words.mapTip01 + ":" + this.info.Address;
                            pageObj.fn.showMapInfo(storeInfo, this);
                            var storeInfo = this.info;
                            var html =
                                '<li ><div class="md-itm" storeSysNo="' + storeInfo.SysNo + '" areaCode="' + storeInfo.AreaCode + '">' +
                                '<div class="tit cf">' + storeInfo.StoreName + '</div>' +
                                '<div class="txt">' + storeInfo.Address + '</div>' +
                                '</div></li>';
                            $(".slect-store").first().html(html);
                        });
                    }
                    var html = storeArr.join('');
                    $(".md-ul").first().html(html);
                    //到店加載第一個數據
                    var h = $(".md-ul li:first").first().html();
                    $(".slect-store").html(h);
                    //移動地圖中心到此店鋪
                    var positonStoreFirst = storeList[0];
                    var lat = positonStoreFirst.GoogleLatLng.split(",")[0];
                    var lng = positonStoreFirst.GoogleLatLng.split(",")[1];
                    var positon99 = { lat: parseFloat(lat), lng: parseFloat(lng) };
                    var result_mark99 = new google.maps.Marker({ position: positon99 });
                    result_mark99.info = positonStoreFirst;
                    result_mark99.setMap(map);
                    map.panTo(positon99);
                    var storeInfo = "<b>" + positonStoreFirst.StoreName + "</b><br/>" + pageObj.words.mapTip01 + ":" + positonStoreFirst.Address;
                    pageObj.fn.showMapInfo(storeInfo, result_mark99);
                }, error: pageObj.fn.ajaxError
            });
        }
        //加載所有店鋪
        , loadStoreAll: function () {
            $.ajax({
                url: pageObj.urlArr.getAllStore, type: "post",
                success: function (d) {
                    if (!d.Status) {
                        pageObj.fn.alertMsg(d.Message);
                        return;
                    }
                    if (d.Rows.length == 0) {
                        return;
                    }
                    storeList = d.Rows;
                    var storeArr = [];
                    for (var i = 0; i < d.Rows.length; i++) {
                        var item = d.Rows[i];
                        var html =
                            '<li ><div class="md-itm" storeSysNo="' + item.SysNo + '" areaCode="' + item.AreaCode + '">' +
                            '<div class="tit cf">' + item.StoreName + '</div>' +
                            '<div class="txt">' + item.Address + '</div>' +
                            '</div></li>';
                        storeArr.push(html);
                    }
                    var html = storeArr.join('');
                    $(".md-ul").first().html(html);
                    //到店加載第一個數據
                    var h = $(".md-ul li:first").first().html();
                    $(".slect-store").html(h);
                    //定位店鋪到地圖
                    var firstStore = d.Rows[0];
                    console.log(firstStore);
                    var lat = firstStore.GoogleLatLng.split(",")[0];
                    var lng = firstStore.GoogleLatLng.split(",")[1];
                    var positon = { lat: parseFloat(lat), lng: parseFloat(lng) };
                    var result_mark = new google.maps.Marker({ position: positon });
                    result_mark.info = firstStore;// { name: item.StoreName, address: item.Address };
                    result_mark.setMap(map);
                    map.panTo(positon);
                    var storeInfo = "<b>" + firstStore.StoreName + "</b><br/>" + pageObj.words.mapTip01 + ":" + firstStore.Address;
                    pageObj.fn.showMapInfo(storeInfo, result_mark);
                }, error: pageObj.fn.ajaxError
            });
        }
        //提交預約單
        , sumitOrder: function () {
            var phoneNumber = document.getElementById("txtPhoneGoStore").value;
            if (phoneNumber == "") {
                pageObj.fn.alertMsg(pageObj.words.ckv_ContractPhone);
                return;
            }
            var selectParentObj;
            if (doorOrStore == 1) {
                selectParentObj = $("#doorMalfun");
            } else {
                selectParentObj = $("#storeMalfun");
            }
            var brandSysNo = selectParentObj.find("div[typeid=Brand] .cur").first().attr("sysno");
            var brandSysName = selectParentObj.find("div[typeid=Brand] .cur").first().html();  //取品牌名称 
            var phoneModel = selectParentObj.find("div[typeid=Model] .cur").first().attr("modelsysno");
            var phoneModelName = selectParentObj.find("div[typeid=Model] .cur").first().html();  //取型号名称 
            var malfunctionSysNo = selectParentObj.find("div[typeid=Trouble] .cur").first().attr("malfunctionsysno");
            var malfunctionSysName = selectParentObj.find("div[typeid=Trouble] .cur").first().html();  //取故障名称
            //if (brandSysNo==undefined) {
            //    pageObj.fn.alertMsg(pageObj.words.ckv_brand);
            //    return;
            //} 
            //if (phoneModel == undefined) {
            //    pageObj.fn.alertMsg(pageObj.words.ckv_models);
            //    return;
            //}              
            //if (malfunctionSysNo == undefined) {
            //    pageObj.fn.alertMsg(pageObj.words.ckv_selectMalfun);
            //    return;
            //}
            var address = $(".slect-store .md-itm .txt").html();
            //店鋪id
            var stroreSysNo = 0;
            var serviceTypeVal = $(".rws-tab>.nav-tab .cur").attr("data-role");
            var _serviceType = 1;
            var areaCode = $(".slect-store .md-itm").attr("areaCode");
            debugger
            var _skuSysno = "0";
            //到店
            if (serviceTypeVal == "store") {
                _serviceType = 2;
                stroreSysNo = $(".slect-store .md-itm").attr("storesysno");
                if (stroreSysNo == undefined || stroreSysNo == "") {
                    pageObj.fn.alertMsg(pageObj.words.ckv_selectStore);
                    return;
                }
                if (minPriceOfSkuInfoStore != undefined && minPriceOfSkuInfoStore != null) {
                    _skuSysno = minPriceOfSkuInfoStore.SysNo;
                }
            }
            //上門
            else if (serviceTypeVal == "door") {
                _serviceType = 1;          
                address = document.getElementById("txtDoorAddress").value;
                areaCode = goCustumerDoorAreaCode;
                //if (address == "") {
                //    pageObj.alertMsg(pageObj.words.ckv_address);
                //    return;
                //}
                if (minPriceOfSkuInfoDoor != undefined && minPriceOfSkuInfoDoor != null) {
                    _skuSysno = minPriceOfSkuInfoDoor.SysNo;
                }
            }           
            //if (minPriceOfSkuInfo != undefined && minPriceOfSkuInfo != null) {
            //    _skuSysno = minPriceOfSkuInfo.SysNo;
            //}
            var parame = {
                BrandSysNo: brandSysNo || "0",
                ModelSysNo: phoneModel || "0",
                MalfunctionSysNo: malfunctionSysNo || "0",
                ServiceType: _serviceType,
                StroreSysNo: stroreSysNo || "0",
                AreaCode: areaCode || "0",
                Address: address,
                PhoneNumber: phoneNumber,
                SkuSysno: _skuSysno || "0"
            }
            //console.log("訂單數據：");
            //console.log(parame);
            //return;
            $.ajax({
                url: pageObj.urlArr.sumitOrder,
                type: "post",
                data: parame,
                success: function (d) {
                    console.log(d);
                    if (d.Status) {
                        window.location.href = pageObj.urlArr.successPage + "?orderNo=" + d.Data + "&brandSysName=" + brandSysName + "&phoneModelName=" + phoneModelName + "&malfunctionSysName=" + malfunctionSysName;
                    } else {
                        if (d.Message == "") {
                            pageObj.fn.alertMsg(pageObj.words.orderFail);
                        } else {
                            pageObj.fn.alertMsg(d.Message);
                        }
                    }
                }, error: pageObj.fn.ajaxError
            });
        }
        //根據手機品牌加載其下的手機型號列表
        , loadPhoneModels: function (brandSysNo, type) {
            //加載選中品牌下手機型號列表 
            var phoneModels=null;
             //if (doorOrStore == 1) {
            if (type == 1) {
                //上門
                phoneModels = phoneModelsDoor;
            } else {
                //到店
                phoneModels = phoneModelsStore;
            }
            var modelsList = phoneModels.filter(w => w.ParentSysNo == brandSysNo);
            if (modelsList.length == 0) {
                return;
            }
            var modelHtml = new Array();
            for (var i = 0; i < modelsList.length; i++) {
                var item = modelsList[i];
                ////檢查此手機型號下有無故障列表，沒有則排除
                if (item.MalfunctionOfProCagesList.length == 0) {
                    continue;
                }
                //for (var g = 0; g < item.MalfunctionOfProCagesList.length; g++) {
                //    var malfunction = item.MalfunctionOfProCagesList[g];
                //    //是否有sku
                //   var ckSkuArr=  skuListJson.filter(w => w.MalfunctionsSysNo == malfunction.MalfunctionsSysNo && w.ProductCategorySysNo == item.SysNo);
                //   if (true) {
                //   }
                //}
                modelHtml.push('<p modelSysNo="' + item.SysNo + '">' + item.CategoryName + '</p>');
            }
            if (type == 1) {
                $("#doorMalfun .box[typeid=Model]").html(modelHtml.join(''));
            } else {
                $("#storeMalfun .box[typeid=Model]").html(modelHtml.join(''));
            }
            //document.getElementById("Model").innerHTML = modelHtml.join('');
        }
        //根據手機型號加載其下的故障類型
        , loadMalfuns: function (modelSysNo, type) {
            var modelInfo = null;
            if (type == 1) {
                modelInfo = phoneModelsDoor.find(w => w.SysNo == modelSysNo);
            } else {
                modelInfo = phoneModelsStore.find(w => w.SysNo == modelSysNo);
            }
            //var modelInfo = phoneModels.find(w => w.SysNo == modelSysNo);
            if (modelInfo == undefined || modelInfo == null) {
                return;
            }
            var htmlArr = new Array();
            for (var g = 0; g < modelInfo.MalfunctionOfProCagesList.length; g++) {
                var item = modelInfo.MalfunctionOfProCagesList[g];
                //檢查此型號、故障類型下是否有sku，如果沒有sku，則排除此故障類型
                var ckHaveSku = skuListJson.filter(w => w.ProductCategorySysNo == modelSysNo && w.MalfunctionsSysNo == item.MalfunctionsSysNo);
                console.log(ckHaveSku);
                if (ckHaveSku == null || ckHaveSku.length == 0) {
                    continue;
                }
                htmlArr.push('<p malfunctionSysNo="' + item.MalfunctionsSysNo + '">' + item.MalfunctionName + '</p>');
            }
            //document.getElementById("Trouble").innerHTML = htmlArr.join('');
            if (type == 1) {
                $("#doorMalfun .box[typeid=Trouble]").html(htmlArr.join(''));
            } else {
                $("#storeMalfun .box[typeid=Trouble]").html(htmlArr.join(''));
            }
        }
        //故障選擇確定按鈕 事件
        , sureMalfunBtn: function () {
            console.log('確定');
            //debugger
            var brandSysNo = "", phoneModel = "", malfunctionSysNo="";
            if (doorOrStore == 1) {              
                brandSysNo =$("#doorMalfun div[typeid=Brand] .cur").attr("sysno");
                phoneModel = $("#doorMalfun div[typeid=Model] .cur").attr("modelsysno");
                malfunctionSysNo = $("#doorMalfun div[typeid=Trouble] .cur").attr("malfunctionsysno");
            } else {
                brandSysNo = $("#storeMalfun div[typeid=Brand] .cur").attr("sysno");
                phoneModel = $("#storeMalfun div[typeid=Model] .cur").attr("modelsysno");
                malfunctionSysNo = $("#storeMalfun div[typeid=Trouble] .cur").attr("malfunctionsysno");
            }
            if (brandSysNo == undefined) {
                $('.pop-gz').hide();
                return;
            }
            if (phoneModel == undefined) {
                pageObj.fn.alertMsg(pageObj.words.ckv_models);
                return;
            }
            if (malfunctionSysNo == undefined) {
                pageObj.fn.alertMsg(pageObj.words.ckv_selectMalfun);
                return;
            }
            var skuSelectedArr = skuListJson.filter(w => w.ProductCategorySysNo == phoneModel && w.MalfunctionsSysNo == malfunctionSysNo);
            console.log('-------skuSelectedArr:');
            console.log(skuSelectedArr);
            //找出最小價格
            var minPrice = Math.min.apply(Math, skuSelectedArr.map(function (o) { return o.Price }))
            //找出價格最小的對象
            var minPriceObj_in=null;
            if (doorOrStore == 1) {
                minPriceOfSkuInfoDoor = skuSelectedArr.find(w => w.Price == minPrice);
                minPriceObj_in = minPriceOfSkuInfoDoor;
            } else {
                minPriceOfSkuInfoStore = skuSelectedArr.find(w => w.Price == minPrice);
                minPriceObj_in = minPriceOfSkuInfoStore;
            }          
            if (minPriceObj_in == null || minPriceObj_in == undefined) {
                minPriceObj_in = { Price: "0.00" };
            }
            console.log(minPriceObj_in);
            var priceTxt = pageObj.words.Currency + parseFloat(minPrice).toFixed(2);
            if (doorOrStore == 1) {
                $("#minPriceValueDoor").html(priceTxt).show();
                $("#minPriceValueStore").hide();
            } else {
                $("#minPriceValueDoor").hide();
                $("#minPriceValueStore").html(priceTxt).show();
            }
            //document.getElementById("minPriceValue").innerHTML = pageObj.words.Currency + parseFloat(minPrice).toFixed(2);
            $('.pop-gz').hide();
        }
        //让上门输入手机号失去焦点
        , inputPhoneBlur: function () {
            $("#txtPhoneGoStore").blur();
        }
        //根據地區名稱匹配地區id
        , marchPositonAreaId: function (areaName) {
            if (areaName == "") {
                return;
            }
            $.ajax({
                url: pageObj.urlArr.getStores,
                type: "post",
                data: { countyName: areaName },
                success: function (d) {
                    if (!d.Status) {
                        pageObj.fn.alertMsg(pageObj.words.handleError + d.Message);
                        return;
                    }
                    if (d.Data.length == 0) {
                        console.log("沒有匹配到上門區縣id");
                        return;
                    }
                    goCustumerDoorAreaCode = d.Data[0].AreaCode || "0";
                    console.log("匹配到的上門地區id=" + goCustumerDoorAreaCode);
                }, error: pageObj.fn.ajaxError
            });
        }
        //地區定位到店鋪位置
        , mapPantoStore: function (storeSysNo) {
            if (storeList == undefined || storeList==null) {
                return;
            }
            var store = storeList.find(w => w.SysNo == storeSysNo);
            if (store == undefined || store == null) {
                return;
            }
            var lat = store.GoogleLatLng.split(",")[0];
            var lng = store.GoogleLatLng.split(",")[1];
            var positon = { lat: parseFloat(lat), lng: parseFloat(lng) };
            //地圖中心移動到此店       
            var result_mark = new google.maps.Marker({ position: positon });
            result_mark.info = store;// { name: item.StoreName, address: item.Address };
            result_mark.setMap(map);
            map.panTo(positon);
            var storeInfo = "<b>" + store.StoreName + "</b><br/>" + pageObj.words.mapTip01 + ":" + store.Address;
            pageObj.fn.showMapInfo(storeInfo, result_mark);
        }
        //加載手機品牌，根據上門、到店tab切換，t=1上門，t=2到店
        , loadBrandOnTabChange: function (t) {            
            if (t == 1) {
                var hArr = new Array();
                for (var i = 0; i < phoneBrandsDoor.length; i++) {
                    var item = phoneBrandsDoor[i];
                    hArr.push('<p sysNo="' + item.SysNo + '">' + item.CategoryName + '</p>');
                }
                var html = hArr.join("");
                $("#doorMalfun .box[typeid=Brand]").html(html).show();
                //console.log('已加載上門品牌');
            } else if (t == 2) {
                var hArrStore = new Array();
                for (var i = 0; i < PhoneBrandsStore.length; i++) {
                    var item = PhoneBrandsStore[i];
                    hArrStore.push('<p sysNo="' + item.SysNo + '">' + item.CategoryName + '</p>');
                }            
                var html = hArrStore.join("");
                $("#storeMalfun .box[typeid=Brand]").html(html).show();
                //console.log('已加載到店品牌');
            }            
        }
        //設置熱門跳轉過來故障選中,type=1上門，2=到店
        ,setHotMalfuciton: function (type) {
            if (pageObj.hotPageParames.brandCategorySysno == "" || pageObj.hotPageParames.brandCategorySysno == "0") {
                return;
            }
            //如果spu支持上門和到店，則上門和到店的故障都要設置選中
            var parentDiv;
            if (type== 1) {
                parentDiv = $("#doorMalfun");
                var doorMach = phoneBrandsDoor.filter(w => w.SysNo == pageObj.hotPageParames.brandCategorySysno);
                if (doorMach.length == 0) {
                    return;
                }
                //檢查型號下是否有此故障，沒有則返回
                var pm = phoneModelsDoor.find(w => w.SysNo == pageObj.hotPageParames.typeCategorySysno);
                if (pm == undefined || pm==null) {
                    return;
                }
                var c= pm.MalfunctionOfProCagesList.filter(x => x.MalfunctionsSysNo == pageObj.hotPageParames.malfunctionsSysNo);
                if (c.length==0) {
                    return;
                }
            } else {
                parentDiv = $("#storeMalfun");
                var storeMach = PhoneBrandsStore.filter(w => w.SysNo == pageObj.hotPageParames.brandCategorySysno);
                if (storeMach.length == 0) {
                    return;
                }
                //檢查型號下是否有此故障，沒有則返回
                var pm = phoneModelsStore.find(w => w.SysNo == pageObj.hotPageParames.typeCategorySysno);
                if (pm == undefined || pm == null) {
                    return;
                }
                var c = pm.MalfunctionOfProCagesList.filter(x => x.MalfunctionsSysNo == pageObj.hotPageParames.malfunctionsSysNo);
                if (c.length == 0) {
                    return;
                }
            }
            setCurMalfun(type, parentDiv);
            //setCurMalfun(2, $("#storeMalfun"));
            //type=1上門，2=到店
            function setCurMalfun(type, parentObj) {
                //if (type == 1) {
                //    var doorMach = phoneBrandsDoor.filter(w => w.SysNo == pageObj.hotPageParames.brandCategorySysno);
                //    if (doorMach.length==0) {
                //        return;
                //    }
                //} else {
                //    var storeMach = PhoneBrandsStore.filter(w => w.SysNo == pageObj.hotPageParames.brandCategorySysno);
                //    if (storeMach.length==0) {
                //        return;
                //    }
                //}
                //處理熱門跳轉過來的參數
                //品牌列表設置選中
                parentObj.find("div[typeid=Brand] p").removeClass("cur");
                parentObj.find("div[typeid=Brand] p[sysno='" + pageObj.hotPageParames.brandCategorySysno + "']").addClass("cur");
                //加載型號列表
                pageObj.fn.loadPhoneModels(pageObj.hotPageParames.brandCategorySysno, type);
                //設置型號選中
                parentObj.find("div[typeid=Model] p[modelsysno='" + pageObj.hotPageParames.typeCategorySysno + "']").addClass("cur");
                //加載故障列表
                pageObj.fn.loadMalfuns(pageObj.hotPageParames.typeCategorySysno, type);
                //設置故障類型選中
                parentObj.find("div[typeid=Trouble] p[malfunctionsysno='" + pageObj.hotPageParames.malfunctionsSysNo + "']").addClass("cur");
                //根據sku主鍵查找價格
                var minPriceObj_in = null;
                if (pageObj.hotPageParames.skuSysNO != "" && pageObj.hotPageParames.skuSysNO != "0") {
                    if (type == 1) {
                        minPriceOfSkuInfoDoor = skuListJson.find(w => w.SysNo == pageObj.hotPageParames.skuSysNO);
                        minPriceObj_in = minPriceOfSkuInfoDoor;
                    } else {
                        minPriceOfSkuInfoStore = skuListJson.find(w => w.SysNo == pageObj.hotPageParames.skuSysNO);
                        minPriceObj_in = minPriceOfSkuInfoStore;
                    }
                } else {
                    var skuSelectedArr = skuListJson.filter(w => w.ProductCategorySysNo == pageObj.hotPageParames.typeCategorySysno && w.MalfunctionsSysNo == pageObj.hotPageParames.malfunctionsSysNo);
                    console.log('-------skuSelectedArr:');
                    console.log(skuSelectedArr);
                    //找出最小價格
                    var minPrice = Math.min.apply(Math, skuSelectedArr.map(function (o) { return o.Price }))
                    //找出價格最小的對象
                    //var minPriceObj_in = null;
                    if (type == 1) {
                        minPriceOfSkuInfoDoor = skuSelectedArr.find(w => w.Price == minPrice);
                        minPriceObj_in = minPriceOfSkuInfoDoor;
                    } else {
                        minPriceOfSkuInfoStore = skuSelectedArr.find(w => w.Price == minPrice);
                        minPriceObj_in = minPriceOfSkuInfoStore;
                    }  
                }            
                if (minPriceObj_in == null || minPriceObj_in == undefined) {
                    console.log("没有从sku集合中匹配到热门传来的主键id，确保此sku主键的关联数据是启用的");
                    minPriceObj_in = { Price: "0.00" };
                }
                //設置價格
                var priceTxt = pageObj.words.Currency + parseFloat(minPriceObj_in.Price).toFixed(2);
                if (type== 1) {
                    document.getElementById("minPriceValueDoor").innerHTML = priceTxt;
                } else {
                    document.getElementById("minPriceValueStore").innerHTML = priceTxt;
                }
                pageObj.fn.getMalfunTxtToShow(type);
            }
        }
        //type=1上門，2=到店
        //獲取當前選中的故障文本，賦值給故障顯示標籤
        , getMalfunTxtToShow: function (type) {
            var curObj;
            if (type == 1) {
                curObj = $("#doorMalfun .rep-box .cur");
            } else {
                curObj = $("#storeMalfun .rep-box .cur");
            }
            var selecteMauterArr = new Array();
            curObj.each(function (index, element) {
                selecteMauterArr.push($(element).text());
            });
            console.log(selecteMauterArr);
            var gzTxt = selecteMauterArr.join(" ");
             //设置维修故障    
            if (type == 1) {
                $("#doorGzTxt").html(gzTxt);
            } else {
                $("#storeGzTxt").html(gzTxt);
            }        
        }
    };//fn結束

    //上門 品牌數據加載
    pageObj.fn.loadBrandOnTabChange(1);
     //到店 品牌數據加載
    pageObj.fn.loadBrandOnTabChange(2);

    //if (pageObj.hotPageParames.brandCategorySysno != "" && pageObj.hotPageParames.brandCategorySysno > 0) {
        if (pageObj.serverType == 1) {
            //切換到上門           
            $(".nav-tab li[data-role=door]").addClass("cur").siblings().removeClass("cur");
            //顯示上門
            $(".row-sm").removeClass("mui-hidden");
            //隱藏到店
            $(".row-md").addClass("mui-hidden");     
        } else if (pageObj.serverType == 2) {
            //切換到到店
            $(".nav-tab li[data-role=store]").addClass("cur").siblings().removeClass("cur");
            //隱藏上門
            $(".row-sm").addClass("mui-hidden");
            //顯示到店
            $(".row-md").removeClass("mui-hidden");       
        }
    //}
        if (pageObj.serverType == 3) {
            pageObj.fn.setHotMalfuciton(1);
            pageObj.fn.setHotMalfuciton(2);
        } else if (pageObj.serverType == 1){
            pageObj.fn.setHotMalfuciton(1);
        } else if (pageObj.serverType ==2) {
            pageObj.fn.setHotMalfuciton(2);
        }    
}();
    ////如果八秒都沒有定位成功，則加載所有店鋪
    //    setTimeout(function () {         
    //        var storeId = $(".slect-store .md-itm").attr("storesysno");
    //        if (storeId == undefined || storeId=="") {
    //            pageObj.loadStoreAll();
    //        }
    //    }, 8000);

function initMap() {
    //默認定位成都
    //30.659634242460026, 104.06582974016158
    map = new google.maps.Map(document.getElementById('mapApi'), {
        center: new google.maps.LatLng(30.659634242460026, 104.06582974016158),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        zoomControl: false,   
        fullscreenControl:false 
    });
    infowindow = new google.maps.InfoWindow;
    //地址id轉換為坐標
    geocoder = new google.maps.Geocoder;
    //地址搜索匹配多個結果
    autocompleteService = new google.maps.places.AutocompleteService();
    pageObj.fn.getPosition();

}